<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/18 上午10:10
 * +-------------------------------------------------------------
 */

namespace app\admin\model;

use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SysAuth extends BaseModel
{
    /**
     * 获取权限列表
     * @return array
     */
    public function getAuthList(): array
    {
        return $this->where('status', 1)->column('title', 'id');
    }


    /**
     * 获取角色权限节点列表
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getAuthorizeNodeListByAdminId($authId): array
    {
        //获取角色选中的权限菜单节点列表
        $checkNodeList = (new SysAuthMenu())->getAuthMenuList($authId);
        //获取所有菜单节点列表
        $nodeList = (new SysMenu())->getMenuList();

        //递归构建树形结构
        return $this->buildChildNode(0, $nodeList, $checkNodeList);
    }

    /**
     * 递归构建树形结构
     * @param $pid
     * @param $nodeList
     * @param $checkNodeList
     * @return mixed
     */
    public function buildChildNode($pid, $nodeList, $checkNodeList)
    {
        $newNodeList = [];
        foreach($nodeList as $v){
            if($v['pid'] == $pid) {
                $v            = array_merge($v, ['field'  => 'node', 'spread' => true]);
                $v['checked'] = in_array($v['id'], $checkNodeList) ? true : false;
                $v['title']   = "{$v['title']}【{$v['href']}】";
                $child = $this->buildChildNode($v['id'], $nodeList, $checkNodeList);
                if(!empty($child)){
                    $v['children'] = $child;
                }
                $newNodeList[] = $v;
            }
        }
        return $newNodeList;
    }
}